package com.zc.framework.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ChineseFontProvider;
import com.itextpdf.text.pdf.HeaderFooter;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.zc.app.shiro.utils.SpringUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.log4j.Logger;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;

/**
 * PDF模板工具类
 * @author lxp
 *
 */
public class PDFTemplateUtils {
	
	private static final Logger log = Logger.getLogger(PDFTemplateUtils.class);
	
	/**
	 * @param template
	 * @return
	 * @throws IOException 
	 */
	public static void buildPdfFile(com.itextpdf.text.pdf.Template template, Rectangle rectangle) throws IOException {
		Document document = null;
		ByteArrayInputStream input = null;
		PdfWriter pdfwriter = null;
		FileOutputStream outputStream = null;
		ByteArrayOutputStream byteOutputStream = null;
        try {
        	FreeMarkerConfigurer freeMarkerConfigurer = (FreeMarkerConfigurer) SpringUtils.getBean("freeMarkerConfigurer");
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template2 = configuration.getTemplate(template.getTemplateName(), 
            		Locale.CHINA, com.itextpdf.text.pdf.Template.ENCODING_UTF8);
            template2.setEncoding(com.itextpdf.text.pdf.Template.ENCODING_UTF8);
            template2.setOutputEncoding(com.itextpdf.text.pdf.Template.ENCODING_UTF8);
            
            byte[] barray = FreeMarkerTemplateUtils.processTemplateIntoString(template2, template.getModel()).getBytes(com.itextpdf.text.pdf.Template.ENCODING_UTF8);
            input = new ByteArrayInputStream(barray);
            
            // 横向： PageSize.A4.rotate(); 纵向：PageSize.A4
            document = new Document(rectangle);
            document.setMargins(0, 0, 35, 0);
            document.addAuthor(template.getCompanyName());
            document.addHeader("company", template.getCompanyName());
            
            if(com.itextpdf.text.pdf.Template.GENERATE_TYPE.FILE.equals(template.getGenerateType())) {
            	outputStream = new FileOutputStream(template.getGeneratePath());
            	pdfwriter = PdfWriter.getInstance(document, outputStream);
            } else if(com.itextpdf.text.pdf.Template.GENERATE_TYPE.IO.equals(template.getGenerateType())){
            	byteOutputStream = new ByteArrayOutputStream();
            	pdfwriter = PdfWriter.getInstance(document, byteOutputStream);
            }
            
            // 设置页眉页脚
            HeaderFooter headerFooter = new HeaderFooter(template.getCompanyName(), template.getCompanyLogo(), Font.DEFAULTSIZE);
            pdfwriter.setPageEvent(headerFooter);
            document.open();
            
            XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document, input, null, 
            		Charset.forName(com.itextpdf.text.pdf.Template.ENCODING_UTF8), new ChineseFontProvider());
        	document.close();
        	
        	if(com.itextpdf.text.pdf.Template.GENERATE_TYPE.IO.equals(template.getGenerateType())){
        		template.setByteArrayInputStream(new ByteArrayInputStream(byteOutputStream.toByteArray()));
        	}
        	
        } catch (Exception e) {
            log.error("Process TradeLeaders Report PDF temple Error" + e.getMessage());
        } finally {
        	if(input != null) {
        		input.close();
        	}
        	if(outputStream != null) {
        		outputStream.close();
        	}
        	if(byteOutputStream != null) {
        		byteOutputStream.close();
        	}
        	if(pdfwriter != null) {
        		pdfwriter.close();
        	}
        }
    }
}
